//
//  MLRefreshControl.swift
//  SinaWeibo
//
//  Created by 李亮亮 on 16/4/14.
//  Copyright © 2016年 Big Fish. All rights reserved.
//

import UIKit

//枚举
enum MLRefreshStatue: Int {
    case Normal = 0     //普通状态
    case Pulling = 1    //准备刷新
    case Refreshing = 2 //正在刷新
}

//刷新控件的高度
private let RefreshViewHeight: CGFloat = 60
class MLRefreshControl: UIControl {

    
    var statue: MLRefreshStatue = .Normal {
     
        didSet {
         
            
            
            
            
        }
    }
    
    
    //
    func endRefreshing() {
        
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.8))
        dispatch_after(delta, dispatch_get_main_queue()) { 
            self.statue = .Normal
        }
    }
    
    
    
    override init(frame: CGRect) {
        // 指定refreshControl的默认大小
        let rect = CGRectMake(0, -RefreshViewHeight, ScreenWidth, RefreshViewHeight)
        super.init(frame: rect)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor.orangeColor()
      
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)

        arrowicon.snp_makeConstraints { (make) -> Void in
            //水平居中 向左偏移 30
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowicon.snp_center)
        }
        
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 实时获取父视图的垂直方向位移 和 -124比较 修改视图状态
        // 需要有一个 监测 用户是否'正在拖拽'滚动视图
        let offsetY = scrollView!.contentOffset.y
        let targetOffsetY = -scrollView!.contentInset.top - RefreshViewHeight
        if scrollView!.dragging {
            if statue == .Pulling && offsetY > targetOffsetY {
                // 只要满足位移大于 -124 且 当前状态是 准备刷新
                print("普通状态")
                statue = .Normal
            } else if statue == .Normal && offsetY < targetOffsetY {
                print("准备刷新")
                statue = .Pulling
            }
        } else {
            // 没有拖拽tableView && 当前状态是 准备刷新 才修改为 正在刷新
            if statue == .Pulling {
                print("正在刷新")
                statue = .Refreshing
                // 转动小菊花
                indicatorView.startAnimating()
                // 隐藏箭头
                arrowicon.hidden = true
            }
        }
    }
    
    // 视图将要移动到父视图上的时候会自动调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        // 获取父视图
        if let myFather = newSuperview as? UIScrollView {
            // KVO
            self.scrollView = myFather
            myFather.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        }
    }
    
    
    private var scrollView: UIScrollView?
    //懒加载子视图
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(text: "下拉起飞", textColor: UIColor.darkGrayColor(), fontSize: 16)
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)

    // 移除对象的属性观察
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
}
